﻿namespace Admin.NET.Application.Service;


/// <summary>
/// 基于EntityBaseId实体的服务基类, 实体没有审计字段
/// </summary>
[ApiDescriptionSettings(KeepName = true)]
public abstract class BaseService<T> : IDynamicApiController where T : EntityBaseId, new()
{
    private readonly IServiceScope _serviceScope;
    protected readonly SqlSugarRepository<T> _rep;

    public BaseService(IServiceScopeFactory scopeFactory)
    {
        _serviceScope = scopeFactory.CreateScope();
        _rep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<T>>();
    }

    public ISugarQueryable<T> Queryable
    {
        get
        {
            return _rep.AsQueryable();
        }
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    protected long AddWithInput(object input)
    {
        var obj = _rep.InsertReturnEntity(input.Adapt<T>());
        return obj.Id;
    }

    /// <summary>
    /// 修改
    /// </summary>
    protected bool UpdateWithInput(object input)
    {
        return _rep.Update(input.Adapt<T>());
    }

    /// <summary>
    /// 通过id查询实体
    /// </summary>
    /// <param name="id"></param>
    protected T SingleById(long id)
    {
        return _rep.InSingle(id);
    }

    /// <summary>
    /// 通过id查询Output
    /// </summary>
    /// <typeparam name="Tout"></typeparam>
    /// <param name="id"></param>
    protected Tout GetById<Tout>(long id)
    {
        var obj = _rep.InSingle(id);
        return obj.Adapt<Tout>();
    }

    /// <summary>
    /// 不启用, 仅仅是个例子
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private bool Delete(long id)
    {
        //  return _rep.FakeDelete(new T() { Id = id }) > 0;
        return false;
    }
}